# Create your models here.
# 报表
from django.db import models
from adm.views import room_list
from adm.models import trans
import datetime
from django.db.models import Q
from django.shortcuts import render
from common.models import Detail
from django.urls import path
from django.http import HttpResponse, JsonResponse
import datetime
import time
import json
from django.db.models import Q
from airconfig.config import config


# 管理员
class Manager():
    def __init__(self):
        self.user = "rjgc"
        self.passwd = "rjgc"

    def login(self, user, passwd):
        if user == self.user and passwd == self.passwd:
            return 0
        else:
            return 1

    def create_report(self, list_room, date1, date2):
        res = dict()
        res["data"] = []
        res["error_code"] = 0
        for loop in list_room:
            detail = Detail.objects.filter(Q(rid=loop) & Q(createtime__range=(date1, date2)))
            changetemptimes = 0
            changespeedtimes = 0
            powerofftimes = 0
            DRnum = 0
            ACworkingtime = 0
            for row in detail:
                DRnum += 1
                if row.cmd == "change_tmp":
                    changetemptimes += 1
                elif row.cmd == "change_fan":
                    changespeedtimes += 1
                elif row.cmd == "power_on" or row.cmd == "power_off":
                    powerofftimes += 1
                ACworkingtime += row.requestDuration
            index = trans(loop)
            temp = dict()
            temp["roomId"] = loop
            temp["changetemptimes"] = changetemptimes
            temp["changespeedtimes"] = changespeedtimes
            temp["totalfee"] = room_list[index].totalCost
            temp["powerofftimes"] = powerofftimes
            temp["DRnum"] = DRnum
            temp["ACworkingtime"] = ACworkingtime
            res["data"].append(temp)
        return res

# 管理员控制器


def log_in(request):
    request.params = json.loads(request.body)
    user = request.params["user"]
    passwd = request.params["passwd"]
    res = dict()
    res["error_code"] = manager.login(user, passwd)
    return JsonResponse(res)
# Create your views here.


def create_report(request):
    request.params = json.loads(request.body)
    roomId = request.params["roomId"]
    date1 = request.params["date1"]
    date2 = request.params["date2"]
    res = manager.create_report(roomId,date1,date2)
    return JsonResponse(res)

manager =Manager()

urlpatterns = [
    path('signup', log_in),
    path('createreport', create_report),
]
